//
//  AppDelegate.swift
//  新浪微博
//
//  Created by 焦林生 on 15/11/3.
//  Copyright © 2015年 焦林生. All rights reserved.
//

import UIKit

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?


    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
        
        //测试归档的用户账户
        print(UserAccountViewModel.sharedUserAccount.userAccount)

        setupAppearance()
        
        window = UIWindow(frame: UIScreen .mainScreen().bounds)
        window?.backgroundColor = UIColor .whiteColor()
        window?.rootViewController = defaultRootViewController
        //显示window
        window?.makeKeyAndVisible()
        
        //监听通知
        NSNotificationCenter.defaultCenter().addObserverForName(LJSwithchRootViewControllerNotification,
            //通知名称,通知中心用来识别通知的
            
            object: nil,//发送通知对象
            queue: nil)//主线程
            { [weak self] (notification) -> Void in
                
                let vc = notification.object != nil ?
                
                    WelcomeViewController() :
                    MainViewController()
                
                //切换控制器
                self?.window?.rootViewController = vc
        }
        
        
        return true
    }
    
    //应用程序进入后台
    func applicationDidEnterBackground(application: UIApplication) {
        
        //清除数据库缓存
        StatusDAL.clearDataCache()
    }
    
    //注销通知
    deinit {
        
        NSNotificationCenter.defaultCenter().removeObserver(self,//监听者
            name: LJSwithchRootViewControllerNotification,
            object: nil)//发送通知对象
    }

    //设置全局外观
    private func setupAppearance() {
    
        //修改导航栏外观 要在控件创建之前设置
        UINavigationBar.appearance().tintColor = lJAppearanceTintColor
        UITabBar.appearance().tintColor = lJAppearanceTintColor
    }
   
  }
// MARK: - 界面切换
//类扩展里面只能存储计算性属性  不能存储存储型属性
extension AppDelegate {
    
    //默认跟控制器
    private var defaultRootViewController: UIViewController {
    
        //1 判断是否登录
        if UserAccountViewModel.sharedUserAccount.userLogin {
        
            return isNewVersion ? NewFeatureController() : WelcomeViewController()
        }
        return MainViewController()
    }

    //2  是否是新版本
    private var isNewVersion: Bool {
        
        //1 获取当前版本
        let currentVersion  = NSBundle.mainBundle().infoDictionary!["CFBundleShortVersionString"] as! String
        let version = Double(currentVersion)!
        
        
        //2 从沙盒加载之前保存的版本
        let sandboxVersionKey = "sandboxVersionKey"
        let sandboxVersion = NSUserDefaults.standardUserDefaults().doubleForKey(sandboxVersionKey)
        
        //3 将当前版本保存到沙盒(用户偏好)
        NSUserDefaults.standardUserDefaults().setDouble(version, forKey: sandboxVersionKey)
        //4 返回比较结果
        return version > sandboxVersion
    }

}

